<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\BaseController;
use App\Mail\SendCode;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class PasswordResetController extends BaseController
{
    public function __construct()
    {
        $this->middleware('check.email.code')->only('resetPasswordByEmail');
    }
    /**
     * 获取邮件的验证码
     */
    public function emailCode(Request $request)
    {
        $request->validate([
            'email'=>'required|email|exists:users'
        ],[
            'email.required' => '邮箱 不能为空',
            'email.email' => '邮箱 格式不合法',
            'email.exists' => '邮箱 尚未注册',
        ]);
        // 发送验证码到邮件
        Mail::to($request->input('email'))->queue(new SendCode($request->input('email')));

        return $this->response->noContent();
    }

    /**
     * 提交邮箱和验证码, 修改密码
     */
    public function resetPasswordByEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email|exists:users',
            'password' => 'required|min:6|max:16|confirmed'
        ],[
            'email.required' => '邮箱 不能为空',
            'email.email' => '邮箱 格式不合法',
            'email.exists' => '邮箱 尚未注册',
            'password.required' => '密码 不能为空',
            'password.min' => '密码 最少6个字符',
            'password.max' => '密码 最多16个字符',
            'password.confirmed' => '两次 密码 不一致',
        ]);

        // 更新邮箱
        $user = User::where('email', $request->email)->first();
        $user->password = bcrypt($request->input('password'));
        $user->save();
        return $this->response->noContent();
    }
}
